#!/bin/bash

# Stock Analyzer Daily Runner Script
# This script runs the stock analyzer with proper environment setup

# Set script directory as working directory
cd /home/Test/ANA

# Set up environment variables
export PYTHONPATH="/home/Test/ANA:$PYTHONPATH"
export PYTHONUNBUFFERED=1

# Create log directory if it doesn't exist
mkdir -p /home/Test/ANA/log
mkdir -p /home/Test/result

# Generate log filename with current date
LOG_DATE=$(date +%Y%m%d)
CRON_LOG="/home/Test/ANA/log/${LOG_DATE}_cron.log"

# Log start time
echo "========================================" >> "$CRON_LOG"
echo "Stock Analyzer Cron Job Started at $(date)" >> "$CRON_LOG"
echo "Working Directory: $(pwd)" >> "$CRON_LOG"
echo "Python Version: $(python3 --version)" >> "$CRON_LOG"
echo "========================================" >> "$CRON_LOG"

# Run the analyzer script
python3 /home/Test/ANA/analyzer.py >> "$CRON_LOG" 2>&1

# Capture exit code
EXIT_CODE=$?

# Log completion
echo "========================================" >> "$CRON_LOG"
echo "Stock Analyzer Cron Job Completed at $(date)" >> "$CRON_LOG"
echo "Exit Code: $EXIT_CODE" >> "$CRON_LOG"
echo "========================================" >> "$CRON_LOG"

# If there was an error, also log to syslog
if [ $EXIT_CODE -ne 0 ]; then
    logger "Stock Analyzer cron job failed with exit code $EXIT_CODE"
fi

exit $EXIT_CODE